package co.yixiang.modules.quartz.service.impl;


import co.yixiang.modules.quartz.service.PcProductParser;
import co.yixiang.modules.shop.domain.YxProductStockOut;
import co.yixiang.modules.shop.service.dto.YxProductStockOutDTO;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * 苏宁爬虫类
 */
@Service
public class SNPcProductParser implements PcProductParser {
    //    @Value("${pc.SUNING_SEARCH_STR}")
    private String SUNING_SEARCH_STR = "http://search.suning.com/{searchKey}/";
    //    @Value("${pc.SUNING_PRICE_STR}")
    private String SUNING_PRICE_STR = "http://pas.suning.com/nspcsale_0_000000000{id}_000000000{id}_{vendor}_140_797_7970101_20268_1000194_9194_11547_Z001_.html";

    //    @Value("${pc.SEARCH_KEY}")
    private String SEARCH_KEY = "{searchKey}";

    /**
     * @param searchKey     商品名称
     * @param count         抓取记录数
     * @param baseProductId 外部商品基础数据配置ID（可为空）
     * @return
     */
    @Override
    public List<YxProductStockOutDTO> parserList(String searchKey, int count, Integer baseProductId) {
        List<YxProductStockOutDTO> products = new ArrayList<YxProductStockOutDTO>();
        try {
            searchKey = URLEncoder.encode(searchKey, "UTF-8").replaceAll("\\+", "%20");
            String searchUrl = SUNING_SEARCH_STR.replace(SEARCH_KEY, searchKey);
            System.out.println("sn: " + searchUrl);

            Document doc = Jsoup.connect(searchUrl).header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36").get();
            //Elements productEles = doc.getElementsByClass("product-list  clearfix");
            Elements productEles = doc.select("#product-list>ul>li");
            if (productEles != null) {
                int size = productEles.size();
                for (int i = 0; i < count; i++) {
                    if (i < size) {
                        Element productEle = productEles.get(i);
                        Element productA = productEle.getElementsByClass("img-block").get(0).getElementsByTag("a").get(0);
                        String url = "https:" + productA.attr("href");
                        String imgUrl = "http:" + productA.getElementsByTag("img").get(0).attr("src");
                        String title = productA.getElementsByTag("img").get(0).attr("alt");
                        //String shop = productEle.getElementsByClass("seller").get(0).attr("salesname");
                        YxProductStockOutDTO product = new YxProductStockOutDTO();
                        Long random = Math.round((Math.random() + 1) * 1000);
                        Integer id = random.intValue() / (i + 1);
                        product.setId(id);
                        product.setTitle(title);
                        product.setPrice("");
                        product.setImage(imgUrl);
                        product.setPname(title);
                        product.setUrl(url);
                        product.setDataSource("苏宁国际");
                        product.setBaseProductId(baseProductId);
                        // product.setSeller(shop);
                        //设置商品轮播图
                        Document detailDoc = Jsoup.connect(url).get();
                        Elements elements = detailDoc.select(".imgzoom-thumb-main>ul>li");
                        StringBuffer result = new StringBuffer();
                        List<Map<String, Object>> sliderImageList = new ArrayList<>();
                        if (elements != null || elements.size() != 0) {
                            for (Element element : elements) {
                                //获得每个图片的url
                                Map<String, Object> map = new LinkedHashMap<>();
                                String pictureUrl = "https:" + element.select("img").attr("src-large");
                                map.put("pictureUrl", pictureUrl);
                                map.put("check", false);
                                sliderImageList.add(map);

                            }
                        }
                        product.setSliderImage(sliderImageList);
                        products.add(product);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return products;
    }

    /**
     * 内部商品管理库==>管理商品==>查询苏宁外部图片
     *
     * @param searchKey     商品名称
     * @param count         抓取记录数
     * @param baseProductId 外部商品基础数据配置ID（可为空）
     * @return
     */
    @Override
    public List<YxProductStockOutDTO> findExternalImages(String searchKey, int count, Integer baseProductId) {
        List<YxProductStockOutDTO> products = null;
        try {
            searchKey = URLEncoder.encode(searchKey, "UTF-8").replaceAll("\\+", "%20");
            String searchUrl = SUNING_SEARCH_STR.replace(SEARCH_KEY, searchKey);
            System.out.println("sn: " + searchUrl);

            Document doc = Jsoup.connect(searchUrl).header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36").get();
            Elements productEles = doc.select("#product-list>ul>li");
            if (productEles.size()>0) {
                products = new ArrayList<YxProductStockOutDTO>();
                int size = productEles.size();
                YxProductStockOutDTO product = new YxProductStockOutDTO();
                //首图
                List<Map<String, Object>> figureImageList = new ArrayList<>();
                //轮播图
                List<Map<String, Object>> sliderImageList = new ArrayList<>();
                for (int i = 0; i < count; i++) {
                    if (i < size) {
                        Element productEle = productEles.get(i);
                        Element productA = productEle.getElementsByClass("img-block").get(0).getElementsByTag("a").get(0);
                        String url = "https:" + productA.attr("href");
                        Document detailDoc = Jsoup.connect(url).get();
                        Elements elements = detailDoc.select(".imgzoom-thumb-main>ul>li");
                        if (elements != null || elements.size() != 0) {
                            for (Element element : elements) {
                                Long random = Math.round((Math.random() + 1) * 1000);
                                Integer figureId = random.intValue() / (i + 1);
                                Integer sliderId = random.intValue() / (i + 1);
                                //获得每个图片的url
                                String pictureUrl = "https:" + element.select("img").attr("src-large");
                                //首图
                                Map<String, Object> figureMap = new LinkedHashMap<>();
                                figureMap.put("id", figureId);
                                figureMap.put("image", pictureUrl);
                                figureImageList.add(figureMap);
                                //轮播图
                                Map<String, Object> sliderMap = new LinkedHashMap<>();
                                sliderMap.put("id", sliderId);
                                sliderMap.put("pictureUrl", pictureUrl);
                                sliderMap.put("check", false);
                                sliderImageList.add(sliderMap);

                            }
                        }
                    }
                }
                product.setSliderImage(sliderImageList);
                product.setFigureImage(figureImageList);
                products.add(product);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return products;
    }


}
